package com.example.blog.common.service.impl;

import com.example.blog.common.exception.ServiceException;
import com.example.blog.common.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Slf4j
@Service
public class LocalFileStorageService implements FileStorageService {
    
    @Value("${storage.upload-dir}")
    private String uploadDir;
    
    @Value("${server.servlet.context-path}")
    private String contextPath;
    
    @Override
    public String store(MultipartFile file, String directory) {
        try {
            String filename = StringUtils.cleanPath(file.getOriginalFilename());
            String extension = StringUtils.getFilenameExtension(filename);
            String newFilename = UUID.randomUUID().toString() + "." + extension;
            
            Path targetLocation = Paths.get(uploadDir)
                    .resolve(directory)
                    .resolve(newFilename)
                    .normalize()
                    .toAbsolutePath();
            
            // 确保目标目录存在
            Files.createDirectories(targetLocation.getParent());
            
            // 保存文件
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回文件访问URL
            return contextPath + "/uploads/" + directory + "/" + newFilename;
            
        } catch (IOException ex) {
            log.error("文件存储失败", ex);
            throw new ServiceException("文件存储失败：" + ex.getMessage());
        }
    }
    
    @Override
    public void delete(String fileUrl) {
        try {
            if (fileUrl != null && fileUrl.startsWith(contextPath + "/uploads/")) {
                String relativePath = fileUrl.substring((contextPath + "/uploads/").length());
                Path filePath = Paths.get(uploadDir).resolve(relativePath).normalize();
                Files.deleteIfExists(filePath);
            }
        } catch (IOException ex) {
            log.error("文件删除失败", ex);
            throw new ServiceException("文件删除失败：" + ex.getMessage());
        }
    }
} 